import { View, ScrollView } from "@tarojs/components";
import Calendar from "@/components/Calendar";
import { getRecordsByDay, getMonthStats, delRecord } from "@/request";
import "./index.less";
import { TRecord } from "@/types";
import { useRef, useState } from "react";
import RecordItem from "../record/RecordItem";
import { Empty } from "@/components";
import Taro from "@tarojs/taro";

const History = () => {
  const [records, setRecords] = useState<TRecord[]>([]);
  const [stats, setStats] = useState<{ [key: string]: number }>({});
  const currentDate = useRef<string>("");

  const handleGetMonth = async (month: string) => {
    const res = await getMonthStats(month);
    setStats(res);
  };

  const handleUpdateDate = async (date?: string) => {
    if (date) {
      currentDate.current = date;
    }
    const res = await getRecordsByDay(date || currentDate.current);
    setRecords(res);
  };

  const handleEdit = () => {};
  const handleDelRecord = async (id: string) => {
    await delRecord(id);
    Taro.showToast({
      title: "删除成功",
    });
    handleUpdateDate();
  };

  return (
    <View className="history">
      <Calendar
        onDateSelect={handleUpdateDate}
        onMonthChange={handleGetMonth}
        stats={stats}
      />
      <ScrollView className="history-records-wrapper" scrollY>
        <View className="history-records">
          {records.length !== 0 ? (
            <>
              {records.map((item) => (
                <RecordItem
                  key={item._id}
                  item={item}
                  handleDelRecord={handleDelRecord}
                  handleEdit={handleEdit}
                />
              ))}
            </>
          ) : (
            <Empty text="当天没有数据" type="white" />
          )}
        </View>
      </ScrollView>
    </View>
  );
};

export default History;
